import { defineStore } from 'pinia'
import { AuthService } from '../services/auth'
import ChartCleanup from '../utils/chartCleanup'
import { ROLES, ROLE_CONSTANTS, ROLE_DISPLAY_NAMES } from '../constants/roleConstants'

// 权限定义
export const PERMISSIONS = {
  TICKET_READ: 'ticket:read',
  TICKET_CREATE: 'ticket:create',
  TICKET_UPDATE: 'ticket:update',
  TICKET_DELETE: 'ticket:delete',
  TICKET_ASSIGN: 'ticket:assign',
  USER_MANAGE: 'user:manage',
  SYSTEM_CONFIG: 'system:config',
  REPORT_VIEW: 'report:view',
  NOTIFICATION_MANAGE: 'notification:manage',
  NOTIFICATION_SEND: 'notification:send',
  FILE_UPLOAD: 'file:upload',
  FILE_DELETE: 'file:delete',
  FILE_MANAGE: 'file:manage'
}

// 角色权限映射
const ROLE_PERMISSIONS = {
  [ROLES.ADMIN]: [
    PERMISSIONS.TICKET_READ,
    PERMISSIONS.TICKET_CREATE,
    PERMISSIONS.TICKET_UPDATE,
    PERMISSIONS.TICKET_DELETE,
    PERMISSIONS.TICKET_ASSIGN,
    PERMISSIONS.USER_MANAGE,
    PERMISSIONS.SYSTEM_CONFIG,
    PERMISSIONS.REPORT_VIEW,
    PERMISSIONS.NOTIFICATION_MANAGE,
    PERMISSIONS.NOTIFICATION_SEND,
    PERMISSIONS.FILE_UPLOAD,
    PERMISSIONS.FILE_DELETE,
    PERMISSIONS.FILE_MANAGE
  ],
  [ROLES.SUPERVISOR]: [
    PERMISSIONS.TICKET_READ,
    PERMISSIONS.TICKET_CREATE,
    PERMISSIONS.TICKET_UPDATE,
    PERMISSIONS.TICKET_ASSIGN,
    PERMISSIONS.USER_MANAGE,
    PERMISSIONS.REPORT_VIEW,
    PERMISSIONS.NOTIFICATION_MANAGE,
    PERMISSIONS.NOTIFICATION_SEND,
    PERMISSIONS.FILE_UPLOAD,
    PERMISSIONS.FILE_DELETE,
    PERMISSIONS.FILE_MANAGE
  ],
  [ROLES.AGENT]: [
    PERMISSIONS.TICKET_READ,
    PERMISSIONS.TICKET_CREATE,
    PERMISSIONS.TICKET_UPDATE,
    PERMISSIONS.TICKET_ASSIGN,
    PERMISSIONS.REPORT_VIEW,
    PERMISSIONS.NOTIFICATION_SEND,
    PERMISSIONS.FILE_UPLOAD
  ],
  [ROLES.CUSTOMER]: [
    PERMISSIONS.TICKET_READ,
    PERMISSIONS.TICKET_CREATE
  ],
  [ROLES.READONLY]: [
    PERMISSIONS.TICKET_READ,
    PERMISSIONS.REPORT_VIEW
  ]
}

// 导出角色常量供其他模块使用
export { ROLES, ROLE_CONSTANTS, ROLE_DISPLAY_NAMES }

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
    permissions: [],
    role: null,
    isAuthenticated: false,
    // 权限状态管理
    permissionStatus: {
      loading: false,
      error: null,
      lastCheck: null
    },
    permissionRequests: [],  // 用户的权限申请记录
    permissionCache: new Map(),  // 权限验证缓存（使用Map以支持快速查找）
    authSyncEnabled: false,  // 是否启用多标签页同步
    tokenRefreshTimer: null  // 定时刷新token的定时器
  }),

  getters: {
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    },
    
    hasRole: (state) => (role) => {
      return state.role === role
    },
    
    canManageTickets: (state) => {
      return state.permissions.includes(PERMISSIONS.TICKET_ASSIGN) || 
             state.permissions.includes(PERMISSIONS.USER_MANAGE)
    },
    
    canViewReports: (state) => {
      return state.permissions.includes(PERMISSIONS.REPORT_VIEW)
    },
    
    userDisplayName: (state) => {
      // 优先显示职位，如果没有职位则显示全名，最后显示用户名
      if (state.user?.position) {
        return state.user.position
      }
      if (state.user?.fullName) {
        return state.user.fullName
      }
      if (state.user?.name) {
        return state.user.name
      }
      if (state.user?.username) {
        return state.user.username
      }
      // 如果都没有，返回空字符串而不是"未知用户"
      return ''
    }
  },

  actions: {
    // 登录
    async login(credentials) {
      try {
        // 调用真实的后端API
        const response = await AuthService.login(credentials)
        
        console.log('🔍 登录响应数据:', response)
        console.log('🔍 响应类型:', typeof response)
        console.log('🔍 response.user:', response.user)
        console.log('🔍 response.token:', response.token)
        
        this.user = response.user
        this.token = response.token
        
        // 获取角色信息（必须有role，否则抛出错误）
        const userRole = response.user?.role
        if (!userRole) {
          console.error('❌ 登录响应中缺少角色信息!', response)
          throw new Error('登录响应数据不完整：缺少角色信息')
        }
        this.role = userRole.toLowerCase()
        this.permissions = ROLE_PERMISSIONS[this.role] || []
        this.isAuthenticated = true
        
        // 验证角色是否有效
        if (!['admin', 'agent', 'customer', 'supervisor', 'readonly'].includes(this.role)) {
          console.error('❌ 无效的角色:', this.role)
          throw new Error(`无效的角色: ${this.role}`)
        }
        
        console.log('✅ 用户信息设置完成:', {
          user: this.user,
          role: this.role,
          permissions: this.permissions
        })
        
        // 保存到localStorage
        this.saveAuthData()
        
        // 启动权限同步和定时刷新
        this.setupAuthSync()
        this.startTokenRefresh(10)  // 每10分钟刷新一次
        
        return { success: true, message: '登录成功' }
      } catch (error) {
        console.error('❌ 登录处理失败:', error)
        // 优先使用后端返回的错误消息
        const errorMessage = error.message || error.response?.data?.message || '登录失败，请检查用户名和密码'
        return { success: false, message: errorMessage }
      }
    },

    // 注册
    async register(userData) {
      try {
        // 调用真实的后端API
        const response = await AuthService.register(userData)
        
        return { success: true, message: '注册成功，请登录' }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    // 登出
    logout() {
      try {
        // 停止定时刷新
        this.stopTokenRefresh()
        
        // 清理所有图表实例
        if (typeof window !== 'undefined') {
          ChartCleanup.cleanupAllCharts().catch(error => {
            console.warn('Chart cleanup error:', error)
          })
        }
        
        this.user = null
        this.token = null
        this.permissions = []
        this.role = null
        this.isAuthenticated = false
        
        // 清除localStorage
        AuthService.logout()
        localStorage.removeItem('auth')
        localStorage.removeItem('token')
        localStorage.removeItem('user_info')
        
        // 清除所有store状态
        if (typeof window !== 'undefined' && window.pinia) {
          // 清理其他store的状态
          try {
            const { useTicketsStore } = require('../store/tickets')
            const { useUserStore } = require('../store/user')
            const ticketsStore = useTicketsStore()
            const userStore = useUserStore()
            
            ticketsStore.$reset()
            userStore.$reset()
          } catch (error) {
            console.warn('Store cleanup error:', error)
          }
        }
      } catch (error) {
        console.error('Logout error:', error)
        // 即使出错也要清理基本状态
        this.user = null
        this.token = null
        this.permissions = []
        this.role = null
        this.isAuthenticated = false
        localStorage.clear()
      }
    },

    // 检查权限
    checkPermission(permission) {
      return this.permissions.includes(permission)
    },

    // 检查角色
    checkRole(role) {
      return this.role === role
    },

    // 更新用户信息
    updateUser(userData) {
      if (this.user) {
        this.user = { ...this.user, ...userData }
        this.saveAuthData()
      }
    },

    // 保存认证数据
    saveAuthData() {
      const authData = {
        user: this.user,
        token: this.token,
        permissions: this.permissions,
        role: this.role,
        isAuthenticated: this.isAuthenticated
      }
      localStorage.setItem('auth', JSON.stringify(authData))
    },

    // 加载认证数据
    loadAuthData() {
      try {
        const authData = localStorage.getItem('auth')
        if (authData) {
          const parsed = JSON.parse(authData)
          this.user = parsed.user
          this.token = parsed.token
          this.permissions = parsed.permissions || []
          this.role = parsed.role
          this.isAuthenticated = parsed.isAuthenticated || false
          return true
        }
      } catch (error) {
        console.warn('Failed to load auth data:', error)
      }
      return false
    },

    // 模拟注册API
    async mockRegister(userData) {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      const { username, email, password, role } = userData
      
      // 模拟用户名和邮箱唯一性检查
      const existingUsers = this.getExistingUsers()
      
      if (existingUsers.some(user => user.username === username)) {
        throw new Error('用户名已存在')
      }
      
      if (existingUsers.some(user => user.email === email)) {
        throw new Error('邮箱已被注册')
      }
      
      // 模拟注册成功
      const newUser = {
        id: Date.now(),
        username,
        email,
        password, // 保存密码用于登录验证
        name: username, // 默认使用用户名作为显示名称
        role,
        avatar: null,
        createdAt: new Date().toISOString()
      }
      
      // 保存到本地存储（模拟数据库）
      this.saveUserToLocal(newUser)
      
      return { user: newUser }
    },

    // 获取已存在的用户（模拟数据库查询）
    getExistingUsers() {
      try {
        const users = localStorage.getItem('registered_users')
        return users ? JSON.parse(users) : []
      } catch (error) {
        return []
      }
    },

    // 保存用户到本地存储（模拟数据库保存）
    saveUserToLocal(user) {
      try {
        const existingUsers = this.getExistingUsers()
        existingUsers.push(user)
        localStorage.setItem('registered_users', JSON.stringify(existingUsers))
      } catch (error) {
        console.error('Failed to save user:', error)
      }
    },

    // 模拟登录API
    async mockLogin(credentials) {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟用户数据 - 匹配后端测试账号
      const mockUsers = {
        admin: {
          id: 1,
          username: 'admin',
          name: '系统管理员',
          email: 'admin@example.com',
          role: ROLES.ADMIN,
          avatar: null
        },
        agent1: {
          id: 2,
          username: 'agent1',
          name: '客服A',
          email: 'agent1@example.com',
          role: ROLES.AGENT,
          avatar: null
        },
        customer1: {
          id: 3,
          username: 'customer1',
          name: '客户A',
          email: 'customer1@example.com',
          role: ROLES.CUSTOMER,
          avatar: null
        }
      }
      
      const { username, password } = credentials
      
      // 首先检查注册的用户
      const registeredUsers = this.getExistingUsers()
      const registeredUser = registeredUsers.find(user => 
        user.username === username && user.password === password
      )
      
      if (registeredUser) {
        return {
          user: registeredUser,
          token: 'mock-registered-token-' + Date.now()
        }
      }
      
      // 然后检查预设用户 - 匹配后端测试账号
      if (username === 'admin' && password === 'admin123') {
        return {
          user: mockUsers.admin,
          token: 'mock-admin-token-' + Date.now()
        }
      } else if (username === 'agent1' && password === 'agent123') {
        return {
          user: mockUsers.agent1,
          token: 'mock-agent-token-' + Date.now()
        }
      } else if (username === 'customer1' && password === 'customer123') {
        return {
          user: mockUsers.customer1,
          token: 'mock-customer-token-' + Date.now()
        }
      } else {
        throw new Error('用户名或密码错误')
      }
    },

    // 初始化认证状态
    initAuth() {
      try {
        // 从AuthService获取认证状态
        const isAuth = AuthService.isAuthenticated()
        if (isAuth) {
          const user = AuthService.getCurrentUser()
          const token = AuthService.getToken()
          
          // 确保用户信息有效
          if (user && token) {
            // 验证token有效性
            if (!AuthService.isTokenValid()) {
              console.log('⚠️ Token已过期，清除认证状态')
              this.logout()
              return false
            }
            
            this.user = user
            this.token = token
            this.role = user?.role?.toLowerCase() || user?.role
            this.permissions = ROLE_PERMISSIONS[this.role] || []
            this.isAuthenticated = true
            
            // 启动权限同步和定时刷新
            this.setupAuthSync()
            this.startTokenRefresh(10)
            
            return true
          } else {
            // 如果用户信息无效，清除认证状态
            this.logout()
            return false
          }
        }
        return false
      } catch (error) {
        console.error('初始化认证状态失败:', error)
        this.logout()
        return false
      }
    },

    // ========== 增强的权限管理方法 ==========

    /**
     * 带加载状态的权限检查
     * @param {string} permission - 权限标识
     * @returns {Promise<boolean>}
     */
    async checkPermissionWithLoading(permission) {
      this.permissionStatus.loading = true
      this.permissionStatus.error = null
      
      try {
        // 先检查缓存
        const cached = this.getCachedPermission(permission)
        if (cached !== null) {
          return cached
        }
        
        // 执行权限检查
        const hasPermission = this.permissions.includes(permission)
        
        // 缓存结果
        this.cachePermissionCheck(permission, hasPermission)
        
        this.permissionStatus.lastCheck = new Date().toISOString()
        return hasPermission
      } catch (error) {
        console.error('权限检查失败:', error)
        this.permissionStatus.error = error.message
        return false
      } finally {
        this.permissionStatus.loading = false
      }
    },

    /**
     * 缓存权限检查结果
     * @param {string} permission - 权限标识
     * @param {boolean} result - 检查结果
     */
    cachePermissionCheck(permission, result) {
      this.permissionCache.set(permission, {
        result,
        timestamp: Date.now(),
        ttl: 5 * 60 * 1000  // 缓存5分钟
      })
    },

    /**
     * 获取缓存的权限结果
     * @param {string} permission - 权限标识
     * @returns {boolean|null} 返回缓存的结果，如果缓存不存在或已过期则返回null
     */
    getCachedPermission(permission) {
      const cached = this.permissionCache.get(permission)
      if (!cached) {
        return null
      }
      
      // 检查缓存是否过期
      const now = Date.now()
      if (now - cached.timestamp > cached.ttl) {
        this.permissionCache.delete(permission)
        return null
      }
      
      return cached.result
    },

    /**
     * 清除权限缓存
     */
    clearPermissionCache() {
      this.permissionCache.clear()
      console.log('✅ 权限缓存已清除')
    },

    /**
     * 添加权限申请记录
     * @param {Object} requestData - 申请数据
     */
    addPermissionRequest(requestData) {
      const request = {
        id: Date.now().toString(),
        ...requestData,
        status: 'pending',  // pending, approved, rejected, cancelled
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      
      this.permissionRequests.push(request)
      
      // 保存到localStorage以便持久化
      try {
        localStorage.setItem('permission_requests', JSON.stringify(this.permissionRequests))
      } catch (error) {
        console.warn('保存权限申请记录失败:', error)
      }
      
      console.log('✅ 权限申请已添加:', request)
      return request
    },

    /**
     * 更新权限申请状态
     * @param {string} requestId - 申请ID
     * @param {string} status - 新状态
     * @param {Object} additionalData - 额外数据（如审批意见）
     */
    updatePermissionRequest(requestId, status, additionalData = {}) {
      const request = this.permissionRequests.find(r => r.id === requestId)
      if (!request) {
        console.warn('未找到权限申请记录:', requestId)
        return false
      }
      
      request.status = status
      request.updatedAt = new Date().toISOString()
      Object.assign(request, additionalData)
      
      // 保存到localStorage
      try {
        localStorage.setItem('permission_requests', JSON.stringify(this.permissionRequests))
      } catch (error) {
        console.warn('保存权限申请记录失败:', error)
      }
      
      console.log('✅ 权限申请已更新:', request)
      return true
    },

    /**
     * 删除权限申请记录
     * @param {string} requestId - 申请ID
     */
    deletePermissionRequest(requestId) {
      const index = this.permissionRequests.findIndex(r => r.id === requestId)
      if (index === -1) {
        console.warn('未找到权限申请记录:', requestId)
        return false
      }
      
      this.permissionRequests.splice(index, 1)
      
      // 保存到localStorage
      try {
        localStorage.setItem('permission_requests', JSON.stringify(this.permissionRequests))
      } catch (error) {
        console.warn('保存权限申请记录失败:', error)
      }
      
      console.log('✅ 权限申请已删除:', requestId)
      return true
    },

    /**
     * 加载权限申请记录
     */
    loadPermissionRequests() {
      try {
        const stored = localStorage.getItem('permission_requests')
        if (stored) {
          this.permissionRequests = JSON.parse(stored)
          console.log('✅ 已加载权限申请记录:', this.permissionRequests.length)
        }
      } catch (error) {
        console.warn('加载权限申请记录失败:', error)
        this.permissionRequests = []
      }
    },

    /**
     * 设置权限错误
     * @param {Object} error - 错误对象
     */
    setPermissionError(error) {
      this.permissionStatus.error = error
      console.error('权限错误:', error)
    },

    /**
     * 清除权限错误
     */
    clearPermissionError() {
      this.permissionStatus.error = null
    },

    /**
     * 检查用户是否已申请某权限
     * @param {string} permission - 权限标识
     * @returns {Object|null} 返回申请记录，如果不存在则返回null
     */
    hasRequestedPermission(permission) {
      return this.permissionRequests.find(r => 
        r.permission === permission && 
        (r.status === 'pending' || r.status === 'approved')
      ) || null
    },

    /**
     * 获取待处理的权限申请
     * @returns {Array}
     */
    getPendingRequests() {
      return this.permissionRequests.filter(r => r.status === 'pending')
    },

    /**
     * 设置多标签页权限同步
     */
    setupAuthSync() {
      if (this.authSyncEnabled) {
        console.log('⚠️ 权限同步已启用，跳过重复设置')
        return
      }
      
      // 监听localStorage变化（多标签页同步）
      window.addEventListener('storage', (event) => {
        if (event.key === 'auth') {
          console.log('🔄 检测到其他标签页的认证状态变化')
          
          if (event.newValue) {
            // 其他标签页更新了认证信息
            try {
              const authData = JSON.parse(event.newValue)
              this.user = authData.user
              this.token = authData.token
              this.permissions = authData.permissions || []
              this.role = authData.role
              this.isAuthenticated = authData.isAuthenticated || false
              
              console.log('✅ 已同步其他标签页的认证状态')
            } catch (error) {
              console.error('❌ 同步认证状态失败:', error)
            }
          } else if (event.newValue === null) {
            // 其他标签页登出了
            console.log('🔄 其他标签页已登出，同步登出')
            this.logout()
          }
        }
        
        // 监听token变化
        if (event.key === 'token') {
          if (event.newValue) {
            this.token = event.newValue
            console.log('✅ Token已从其他标签页同步')
          } else if (event.newValue === null) {
            console.log('🔄 Token被清除，触发登出')
            this.logout()
          }
        }
      })
      
      this.authSyncEnabled = true
      console.log('✅ 多标签页权限同步已启用')
    },

    /**
     * 启动定时刷新token
     * @param {number} intervalMinutes - 刷新间隔（分钟）
     */
    startTokenRefresh(intervalMinutes = 10) {
      // 清除现有定时器
      if (this.tokenRefreshTimer) {
        clearInterval(this.tokenRefreshTimer)
      }
      
      // 设置新的定时器
      this.tokenRefreshTimer = setInterval(async () => {
        if (this.isAuthenticated && this.token) {
          try {
            console.log('🔄 定时刷新token...')
            await AuthService.refreshToken()
            
            // 刷新后重新加载用户信息
            const user = AuthService.getCurrentUser()
            const token = AuthService.getToken()
            
            if (user && token) {
              this.user = user
              this.token = token
              this.saveAuthData()
              console.log('✅ Token定时刷新成功')
            }
          } catch (error) {
            console.error('❌ 定时刷新token失败:', error)
            
            // 如果是401错误，说明refresh token也过期了，需要重新登录
            if (error.status === 401 || error.response?.status === 401) {
              console.log('🔒 Refresh token已过期，需要重新登录')
              this.logout()
              if (typeof window !== 'undefined') {
                window.location.href = '/login'
              }
            }
          }
        }
      }, intervalMinutes * 60 * 1000)
      
      console.log(`✅ Token定时刷新已启动，间隔: ${intervalMinutes}分钟`)
    },

    /**
     * 停止定时刷新
     */
    stopTokenRefresh() {
      if (this.tokenRefreshTimer) {
        clearInterval(this.tokenRefreshTimer)
        this.tokenRefreshTimer = null
        console.log('✅ Token定时刷新已停止')
      }
    },

    /**
     * 强制刷新权限（用于权限变更后）
     */
    async forceRefreshPermissions() {
      if (!this.isAuthenticated) {
        console.warn('⚠️ 用户未登录，无法刷新权限')
        return false
      }
      
      try {
        console.log('🔄 强制刷新权限...')
        
        // 刷新token（会同时更新用户信息）
        await AuthService.refreshToken()
        
        // 重新加载认证数据
        const user = AuthService.getCurrentUser()
        const token = AuthService.getToken()
        
        if (user && token) {
          this.user = user
          this.token = token
          this.role = user?.role?.toLowerCase() || user?.role
          this.permissions = ROLE_PERMISSIONS[this.role] || []
          this.saveAuthData()
          
          // 清除权限缓存
          this.clearPermissionCache()
          
          console.log('✅ 权限强制刷新成功')
          return true
        }
        
        return false
      } catch (error) {
        console.error('❌ 强制刷新权限失败:', error)
        return false
      }
    }
  }
})
